package com.wang.kmp.shared.server

import com.wang.kmp.shared.Res
import com.wang.kmp.shared.data.base.BaseResp
import com.wang.kmp.shared.msc
import com.wang.kmp.shared.server.exts.JsonMy
import com.wang.kmp.shared.server.exts.getCauseException
import com.wang.kmp.shared.server.exts.isDebug
import com.wang.kmp.shared.server.exts.replaceNativeImageUri
import com.wang.kmp.shared.server.exts.respondFailed
import com.wang.kmp.shared.server.exts.respondSuccess
import com.wang.kmp.shared.server.exts.respondSuccessDataJson
import io.ktor.serialization.kotlinx.json.json
import io.ktor.server.application.install
import io.ktor.server.cio.CIO
import io.ktor.server.engine.embeddedServer
import io.ktor.server.plugins.contentnegotiation.ContentNegotiation
import io.ktor.server.plugins.statuspages.StatusPages
import io.ktor.server.routing.get
import io.ktor.server.routing.routing
import kotlinx.coroutines.runBlocking
import kotlinx.datetime.Clock
import kotlinx.serialization.MissingFieldException

object MyServer {
    private var isStart = false
    private var port = -1

    @Suppress("OPT_IN_USAGE")
    private val server = embeddedServer(CIO, port = 0) {
        install(ContentNegotiation) {
            json(JsonMy)
        }
        install(StatusPages) {
            exception<Throwable> { call, cause ->
                cause.printStackTrace()
                //参数错误
                val parameterException = cause.getCauseException<MissingFieldException>() ?: cause.getCauseException<IllegalArgumentException>()
                if (parameterException != null) {
                    call.respondFailed(BaseResp.CODE_PARAMETER_FAIL, parameterException.message?.split(",")?.getOrNull(0) ?: "参数错误")
                    return@exception
                }

                //兜底逻辑
                call.respondFailed(BaseResp.CODE_FAIL, "请求失败", if (isDebug) cause.stackTraceToString() else cause.toString())
            }
        }

        routing {
            get("/") {
                call.respondSuccess("测试：${Clock.System.now().toEpochMilliseconds()}")
            }
            get("/api/v1/meditation-scene-category") {
                call.respondSuccessDataJson(Res.string.msc.replaceNativeImageUri())
            }
            get("/api/v1/system/check-update") {
                call.respondSuccess()
            }
        }
    }

    fun start(wait: Boolean) {
        if (isStart) return
        isStart = true
        server.start(wait = wait)
    }

    /**
     * 如果有启动的端口，则返回
     * 否则阻塞到启动成功
     */
    fun getPortAndBlocking(): Int {
        if (port >= 0) return port
        return runBlocking { server.engine.resolvedConnectors().first().port.also { port = it } }
    }
}